package com.huatai.bi.config;

import com.alibaba.nacos.api.utils.NetUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.bi.entity.MqClientNumberEntity;
import com.huatai.bi.entity.MqMqttClientEntity;
import com.huatai.bi.mqtt.MqttClientConnect;
import com.huatai.bi.service.MqClientNumberService;
import com.huatai.bi.service.MqMqttClientService;
import com.huatai.common.util.CollectionUtil;
import com.huatai.common.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;


/**
 * @program: ganghua
 * @description: 检查应用是否完全启动并监测mqtt连接数据
 * @author: songxiude
 * @create: 2024-09-05 09:14
 **/
@Slf4j
@Component
public class SpringBootApplicationRunner implements ApplicationRunner {

	@Value("${server.port}")
	private String port;


	@Autowired
	private MqClientNumberService clientNumberService;

	/**
	 * 执行初始化mqtt连接计数
	 *
	 * @param args
	 * @throws Exception
	 */
	@Override
	public void run(ApplicationArguments args) throws Exception {
		String ipport = NetUtils.localIP() + ":" + port;
		MqClientNumberEntity numberEntity = clientNumberService.getOne(Wrappers.<MqClientNumberEntity>lambdaQuery().eq(MqClientNumberEntity::getIpPort, ipport));
		int size = MqttClientConnect.mqttClients.size();
		if (ObjectUtil.isEmpty(numberEntity)) {
			numberEntity = new MqClientNumberEntity();
			numberEntity.setIpPort(ipport);
		}
		numberEntity.setIsActive(1);
		numberEntity.setClientNumber(size);
		clientNumberService.saveOrUpdate(numberEntity);
		log.info("mqtt初始化完成");
	}
}
